<template>
  <div>
  <FormPanel
    ref="areaMaintain"
    :list="initForm"
    :cols="3"
    :labelWidth="110"
    :isSubmitBtn="false"
    @formChange="formChangeHandle"
  />
  <el-scrollbar style="height: 550px;border: 1px solid rgba(144,147,153,.5);">
    <el-col style="padding: 5px 3px;">

      <el-tree ref="tree" style="margin-top: 12px;" 
        :loading="loading" 
        show-checkbox 
        :data="jsonTree"
        node-key="id" 
        highlight-current 
        
        :expand-on-click-node="false" />

    </el-col>
  </el-scrollbar>

  <!-- table 经销商列表 -->
  <!-- <FilterTable
    height='300'
    ref="table"
    :columns="columns"
    :dataSource="dataSource"
    :isSelectColumn="isSelectColumn"
    :params="flterValue"
    :datakey="'records'"
    :isToperInfo="false"
    columnsRef='origin_personnelInfo_areaMaintain_addDialog_01'
    :onColumnsChange="columns => this.columns = columns"
  >
    <template slot="controls">
    <el-button size="small" type="primary" icon="el-icon-download" v-if="infoBasic == 'edit'" :loading="exportLoading" @click="exportExcel()" >经销商导出</el-button>
    <el-button size="small" type="primary" icon="el-icon-upload" @click="importFun()">经销商导入</el-button>
    <el-button size="small" type="primary" icon="el-icon-plus" @click="dealerHandle">选择经销商</el-button>
    </template>
  </FilterTable> -->
  <div class="dialogBottmView">
    <el-button @click="closeDialog">取 消</el-button>
    <el-button @click="saveDialog" :loading="saveLoading" type="primary">{{ btnText }}</el-button>
  </div>
  <!-- 经销商弹窗 -->
  <!-- <BaseDialog
    title="经销商查询"
    :visible.sync="visibleDealer"
    width="1000px"
    destroyOnClose
    :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
  >
    <dealer-madal ref='addDialogRef' selectType='multiple' v-model="initDealerData" @close="closeDealer" />
  </BaseDialog> -->
  <!-- 区域经理弹窗 -->
  <!-- <BaseDialog
    title="人员选择"
    width="700px"
    destroyOnClose
    :visible.sync="visiblePersonnel"
    :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}" >
    <personnel-madal ref="personnelDialog" selectType='single' @close="closePersonnel" />
  </BaseDialog> -->
  <!-- 导入弹窗 -->
  <!-- <BaseDialog
    :visible.sync="isimportpop"
    destroyOnClose
    title="数据导入"
    :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
  > -->
    <!-- <ImoprtModal
    menuId="-1"
    url="/api/cmscloud.channel/manager/regionalManagerDealer/import"
    @close="closeDealer"
    />
  </BaseDialog> -->
  </div>
</template>
<script>
import { getJsonTree } from '@/utils/index';
import { getComOrgTreeList, } from '@/api/common/org/employeeInfo';
import personnelMadal from '@/pages/cms-common/user'
import dealerMadal from '@/pages/cms-common/dealerdata'
import { dictionary } from '@/utils/dictMixin';
import { insertRegionalManager ,getRegionalManagerById ,searchRegionalDealerManager,updataRegionalManager,exportExcelDealer,updateRegionalManagerJurisdiction,searchRegionalManagerJurisdiction,getOrgDealerTree} from '@/api/cms-api/origin/personnelInfo/areaMaintain';
import { getRegion, getCommunity } from '@/api/cms-common/dealerdata/index';
import { region } from '@/api/cms-common/region';//行政区域
import ImoprtModal from '@/pages/cms-common/import/dealerImport';
import { exportExcelFile } from '@/utils';

import {  getComOrgTreeLists } from '@/api/common/org/employeeInfo';
import { searchDealerOrg, getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
import { getProvince } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import {getChildOrgTreeList,getChildOrgdetail,getOrgBrand,getOrgSeries,saveOrgInfo} from '@/api/common/org/companyOrgManage'

import { findPage } from '@/api/cms-api/origin/originInfo/OEM';


export default {
  components: {
    dealerMadal,personnelMadal,ImoprtModal
  },
  props: {
  value:{
    type: Object,
    default: null
  }
  },
  mixins: [dictionary,region],
  data() {
    this.conf = { add: '保 存', edit: '修 改' };
    return {
      formData:[],
      dealerList:[],
      userId:"",
      recordId:"",//查看时，传递过来的数据ID
      visiblePersonnel: false,
      visibleDealer: false,
      dealerCodeList:[],//列表中包含记录的dealerCode
      initDealerData:{},//经销商弹窗参数
      dataSource:[],
      saveLoading: false,
      isSelectColumn: false,
      initForm: this.initFormFun(),
      flterValue: {}, //参数
      columns: this.creatHeader(),
      isOk:false,
      exportLoading: false,
      isimportpop: false, //导入弹窗默认关闭
      infoBasic:this.value.type,//导出按钮是否显示

      tree: [],
      // jsonTree:[],
      loading: false,
      defaultProps: {
        children: 'children',
        label: 'text'
      },
      params:{
            orgId:0,
            type:10041002,
        },
      dataTree: [],
      checkedList : {},
      orgTree:[], //组织树
      provinceList:{},  //省份列表
    };
  },
  created() {
    //初始化事业部下拉数据
    this.getDeptData();

    this.searchTree();

  },
  computed: {
    //根据传入参数，确定底部按钮名称
    btnText() {
      return this.conf[this.value.type];
    },
    jsonTree() {
      this.tree.forEach(el => (el.label = el.text));
      this.tree.forEach(el => (el.parentId = el.parent));
      return getJsonTree(this.tree);
    }
  },
  watch: {
    isOk(newval,oldval){
    if(newval){
      //如果传入参数不为空，则说明是修改进入，初始化对应数据
      if(this.value != null && this.value.type == "edit"){
      this.init();
      }
    }
    }
  },
  methods: {
    //修改时，初始化页面数据
    async init(){

      // getReview
      let id = this.value.rowData.regionalManagerId;
      //初始化事业部
      this.changeDeptSelect(this.value.rowData.deptId);
      // 更新接口需要的记录 ID
      this.recordId = id;
      // 通过接口 查询区域经理信息
      // await getRegionalManagerById(id,{}).then(res=>{
      //   if(res.resultCode === 200){
      //   this.initForm.forEach(x => {
      //     x.initialValue = res.data[x.fieldName];
      //   });
      //   this.changeDeptSelect(res.data.deptId);
      //   this.userId = res.data.userId;
      //   //TODO 通过上一个页面的rowdata，获取区域经理人员信息，填入对应表单中
      //   // this.initForm[2].initialValue =
      //   }
      // });
      //根据列表页传来数据，回显至页面中
      this.initForm.forEach(x => {
        x.initialValue = this.value.rowData[x.fieldName];
      });
      this.userId = this.value.rowData.userId;



    },
    //搜索数据
    initFormFun() {
      return [
        {//不用了┗|｀O′|┛ 嗷~~
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          initialValue: '',
          hidden: true,
          disabled: true,
          itemList: [],
          change: val => {
            this.changeDeptSelect(val);
          },
          //rules: [{required: true,message: '必填',trigger: 'change'}],
        },
        {//不用了┗|｀O′|┛ 嗷~~
          type: 'SELECT',
          label: '办事处',
          fieldName: 'officeId',
          placeholder: '请选择',
          initialValue: '',
          hidden: true,
          disabled: true,
          itemList: [],
          //rules: [{required: true,message: '必填',trigger: 'change'}],
        },
        {
          type: 'INPUT_TREE',
          label: '所属部门',
          fieldName: 'userOrgId',
          placeholder: '所属部门',
          initialValue: '',
          disabled: true,
          itemList: [],
          //rules: [{ required: true, message: '请选择所属部门', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '区域经理代码',
          fieldName: 'ownerCode',
          placeholder: '请选择',
          initialValue: '',
          readonly:true,
          disabled: true,
          rules: [{required: true,message: '必填',trigger: 'change'}],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => this.personnelHandle()}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '区域经理姓名',
          fieldName: 'userName',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '性别',
          fieldName: 'gender',
          placeholder: '',
          disabled: true,
          initialValue: '',
          itemList: this.createDictList('1002'),
        },
        {
          type: 'INPUT',
          label: '手机',
          fieldName: 'mobilePhone',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '身份证号',
          fieldName: 'certificateId',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '邮箱',
          fieldName: 'eMail',
          placeholder: '',
          disabled: true,
          initialValue: ''
        },
        /*
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'status',
          placeholder: '请选择',
          initialValue: 10031001,
          itemList: this.createDictList('1003'),
          rules: [{required: true,message: '必填',trigger: 'change'}],
        }
        */
      ];
    },
    //搜索获取数据
    changeHandle(val) {
      this.flterValue = val;
    },
    //获取事业部下拉列表数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.initForm[0].itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        this.isOk=true;
      }
    },
    //事业部下拉改变执行方法，级联查询该事业部下的办事处
    async changeDeptSelect(deptId) {
      this.initForm[1].initialValue = '';
      this.initForm[1].itemList = [];
      if (!deptId) {
      } else {
        const res = await getCommunity(deptId);
        if (res.resultCode === 200) {
          this.initForm[1].itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        }
      }
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.$index)}>删除</el-button>
              </div>
            );
          }
        },
        { title: '公司全称', dataIndex: 'dealerName', sorter: true },
        { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
        { title: '经销商简称', dataIndex: 'dealerShortname', sorter: true },
        { title: '经销商类型', dataIndex: 'dealerType', sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.dealerType, '2538')}</span>;
          }
        },
        // { title: '经销商级别', dataIndex: 'field4', sorter: true },
        // { title: '事业部', dataIndex: 'field5', sorter: true },
        // { title: '省份', dataIndex: 'provinceId', sorter: true },
        // { title: '城市', dataIndex: 'cityId', sorter: true },
        // { title: '县区', dataIndex: 'countyId', sorter: true }
        { title: '经销商级别', dataIndex: 'shopLevel', sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.shopLevel, '2540')}</span>;
          }
        },
        { title: '事业部', dataIndex: 'deptName', sorter: true ,width:200},
        { title: '办事处', dataIndex: 'officeName', sorter: true},
        { title: '省份', dataIndex: 'provinceId', sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.provinceId)}</span>;
          }
        },
        { title: '城市', dataIndex: 'cityId', sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.cityId)}</span>;
          }
        },
        { title: '县区', dataIndex: 'districtId', sorter: true,
          render: props => {
            return <span>{this.createRegionText(props.row.districtId)}</span>;
          }
        }
      ];
    },
    // 人员 打开窗口
    personnelHandle() {
      this.visiblePersonnel = true;
    },
    // 人员关闭窗口 -返回数据
    closePersonnel(data) {
      if(data.type != "close" && data.data && data.data[0]){
        let _data = data.data[0];
        this.initForm.find(item => item.fieldName === 'ownerCode').initialValue = _data.employeeNo;//代码
        this.initForm.find(item => item.fieldName === 'userName').initialValue = _data.employeeName;//姓名
        this.initForm.find(item => item.fieldName === 'gender').initialValue = _data.gender;//性别
        this.initForm.find(item => item.fieldName === 'mobilePhone').initialValue = _data.mobilePhone;//手机
        this.initForm.find(item => item.fieldName === 'certificateId').initialValue = _data.certificateId; //身份证号
        this.initForm.find(item => item.fieldName === 'eMail').initialValue = _data.eMail; //邮箱
        this.userId = _data.userId; //userId
      }
      this.visiblePersonnel = data.visible; //关闭弹窗
    },
    // 经销商打开窗口 -传数据
    dealerHandle() {
      this.initDealerData={
        excludeBigCustomer:false,//是否查询大客户经销商，如果查询 true，不查询 false
      }
      this.visibleDealer = true;
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      // this.dataSource = data.data;
      if(data&&data.data&&data.data.length){
        let haveRepeat = false; //是否存在重复信息
        for(let i in data.data){
          let haveId = false; //当前记录是否重复
          for(let j in this.dealerCodeList){
            if(this.dealerCodeList[j] == data.data[i].dealerCode){
              haveId = true;
              haveRepeat = true;
              break;
            }
          }
          if(!haveId){//如果该记录列表中不存在
            this.dealerCodeList.push(data.data[i].dealerCode);
            this.dataSource.push(Object.assign({},data.data[i]));
          }
        }
        if(haveRepeat){
          this.$notify.success({title: '提示信息',message:'存在重复数据，已过滤!'});
        }
      }
      this.visibleDealer = data.visible; //关闭弹窗
      this.isimportpop = false;
    },
    formChangeHandle(data){
      data.status = 10031001;
      this.formData = data;
      this.doSaveDialog();
    },
    //保存按钮
    async saveDialog(){
      console.log(this.$refs['tree'],"this.$refs['tree']");
      console.log(this.$refs['tree'].getCheckedNodes(),"getCheckedNodes");
      console.log(this.$refs['tree'].getHalfCheckedNodes(),"getHalfCheckedNodes");

      

      let checkedNodes = this.$refs['tree'].getCheckedNodes();
      let halfCheckedNodes = this.$refs['tree'].getHalfCheckedNodes();

      let oneArrayChecked = [];
      let twoArrayChecked = [];
      let threeArrayChecked = [];
      let fourArrayChecked = [];
      // let fiveArrayChecked = [];

      let submitArray = [];

      //销售公司是否全选，如果全选，则直接提交销售公司
      for(let i in checkedNodes){
        let node = checkedNodes[i];
        if(node.orgType == 15061001){   
          oneArrayChecked.push(node);
          submitArray.push(node);
          break;
        }
      }

      //如果销售公司未全选
      if(oneArrayChecked.length==0){
        
        //判断事业部是否全选
        for(let i in checkedNodes){
          let node = checkedNodes[i];
          if(node.orgType == 15061005){   
            twoArrayChecked.push(node);
            submitArray.push(node);
          }
        }
        //判断办事处是否全选
        for(let i in checkedNodes){
          let node = checkedNodes[i];
          if(node.orgType == 15061007){   
            threeArrayChecked.push(node);
            //循环判断上级事业部是否全选
            let isHave = false;
            for(let j in twoArrayChecked){
              if(node.parent == twoArrayChecked[j].id){
                isHave = true;
              }
            }
            //如果未全选，则存储该节点
            if(!isHave){
              submitArray.push(node);
            }

          }
        }
        //判断省份是否全选
        for(let i in checkedNodes){
          let node = checkedNodes[i];
          if(node.orgType == 10001001){   
            fourArrayChecked.push(node);
            //循环判断上级办事处是否全选
            let isHave = false;
            for(let j in threeArrayChecked){
              if(node.parent == threeArrayChecked[j].id){
                isHave = true;
              }
            }
            //如果未全选，则存储该节点
            if(!isHave){
              submitArray.push(node);
            }

          }
        }

        //判断经销商是否选择
        for(let i in checkedNodes){
          let node = checkedNodes[i];
          if(node.orgType == 10051001){   
            // fiveArrayChecked.push(node);
            //循环判断上级办事处是否全选
            let isHave = false;
            for(let j in fourArrayChecked){
              if(node.parent == fourArrayChecked[j].id){
                isHave = true;
              }
            }
            //如果未全选，则存储该节点
            if(!isHave){
              submitArray.push(node);
            }

          }
        }


      }

      console.log("submitArray",submitArray);
      //处理提交数据
      for(let i in submitArray){
        let node = submitArray[i];
        node.regionalManagerId = this.recordId;
        node.jurisdictionType = node.orgType;
        node.jurisdictionId = node.id;
        node.jurisdictionName = node.text;
        node.parentId = node.parent;
      }

      this.saveLoading = true;
      // this.formData.userId = this.userId;

      let res = await updateRegionalManagerJurisdiction(submitArray,this.recordId);
      if (res.resultCode === 200) {
        this.$notify.success({title: '提示信息',message:'保存成功!'});
        // 重新加载
        this.closeDialog('refresh');
      }else {
        this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        this.closeDialog();
      }
      
      // this.$refs.areaMaintain.SUBMIT_FORM();
    },
    //执行保存
    async doSaveDialog(){
      this.saveLoading = true;
      this.formData.userId = this.userId;
      this.dataSource.forEach(x => {
        let dealer={};
        dealer.dealerId = x.dealerId;
        dealer.dealerName = x.dealerName;
        dealer.ownerCode = x.dealerCode;
        this.dealerList.push(dealer);
      });
      this.formData.dealerList = this.dealerList;

      let res;
      //如果传入参数不为空并且为修改
      if(this.value != null && this.value.type == "edit"){
        res = await updataRegionalManager(this.formData,this.recordId);
      }else{
        res = await insertRegionalManager(this.formData);
      }
      if (res.resultCode === 200) {
        this.$notify.success({title: '提示信息',message:'保存成功!'});
        // 重新加载
        this.closeDialog('refresh');
      }else {
        this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        this.closeDialog();
      }
    },

    //列表删除
    editHandle(index){
      this.dataSource.splice(index,1);
      this.dealerCodeList.splice(index,1);
    },

    //取消操作
    closeDialog(type) {
      this.$emit('close', { visible: false,type:type});
    },
    //数据导入
    importFun() {
      this.isimportpop = true;
    },
    //关闭导入窗口
    closeHandler(val, type) {
      this.isimportpop = false;
      if (type === 'refresh') {
      // 重新加载
        this.searchData = { ...this.searchData };
      }
    },
    //导出
    async exportExcel(){
      let p = {'regionalManagerId':this.recordId};
      this.exportLoading = true;
      exportExcelDealer(p).then(res => {
        exportExcelFile(res.data,'经销商信息导出');
        this.exportLoading = false;
      });
    },
    // 部门树
    async inputTree() {
      const res = await getComOrgTreeList();
	  var that = res.data;
	//   console.log(that.find(x => x.id == that).orgName);
      that.forEach(el => (el.text = el.text));
      that.forEach(el => (el.value = el.orgId));
      that.forEach(el => (el.parentId = el.parent));
      let orgIdClob = this.initForm.find(x => x.fieldName === 'userOrgId');
      orgIdClob.itemList = getJsonTree(that);
      orgIdClob.initialValue = this.value.rowData.userOrgId;
      orgIdClob.placeholder = this.value.rowData.userOrgName;
    },
    /////////////////////////////////////


    //加载树
    async searchTree() {
      this.loading = true;
      const res = await getOrgDealerTree();

      this.tree = res.data;

      const checkedRes = await searchRegionalManagerJurisdiction({"regionalManagerId":this.recordId});
      let restreejson = checkedRes.data;
      let selectedDealer = []
      for (let j = 0; j < restreejson.length; j++) {
          selectedDealer.push(restreejson[j].jurisdictionId);
      }
      this.$refs['tree'].setCheckedKeys(selectedDealer);

      this.loading = false;

    },

  }
};
</script>

<style lang="less" scoped>
</style>
